package com.zigong.app.ui.activities;

import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.bigkoo.convenientbanner.ConvenientBanner;
import com.bigkoo.convenientbanner.holder.CBViewHolderCreator;
import com.bigkoo.convenientbanner.listener.OnItemClickListener;
import com.google.gson.Gson;
import com.iflytek.cloud.thirdparty.V;
import com.jiongbull.jlog.JLog;
import com.mob.tools.utils.DeviceHelper;
import com.ruihang.generalibrary.utils.SharedPreferencesUtil;
import com.zigong.app.R;
import com.zigong.app.base.BaseActivity;
import com.zigong.app.ui.adapter.holder.AdInfoHolder;
import com.zigong.app.utils.UserManager;

import org.xutils.view.annotation.Event;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 启动页（有广告）
 */
public class SplashAdActivity extends BaseActivity {
    public final static String START_KEY = "START_PAGE_SETTING";
    private final String KEY_AD = "key_ad";
    @BindView(R.id.splash_time)
    protected TextView time_tv;
    @BindView(R.id.splash_images)
    protected ConvenientBanner<Integer> splash_images;
    @BindView(R.id.rl_time)
    protected View vTime;
    private List<Integer> pics;
    private int time;

    private MyCountDownTimer myCountDownTimer;

    private Handler handler;

    private Gson gson;

    private int adCount;

    private CuntDownTask cuntDownRunable;
    private boolean isJump = false;


    private boolean hasCallFinish;
    private static Integer[] imgsRes = {R.mipmap.start1};
    boolean isFirstStart = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initUser();
//        toMain();
//        finish();
//        boolean b=true;
//        if (b) {
//            return;
//        }
        isFirstStart = (boolean) SharedPreferencesUtil.getParam(this, START_KEY, true);

        pics = new ArrayList<>();
        splash_images.setIs169(false);
        if (!isFirstStart) {
            pics = getIntent().getIntegerArrayListExtra("AD_IMGS");
            time = getIntent().getIntExtra("AD_TIME", 3);
//            time_tv.setVisibility(View.VISIBLE);
            vTime.setVisibility(View.VISIBLE);
        } else {
            splash_images.stopTurning();
//            time_tv.setVisibility(View.GONE);
            pics = Arrays.asList(imgsRes);
            vTime.setVisibility(View.GONE);
        }
        splash_images.setCanLoop(false);
        handler = new Handler();

        splash_images.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
                if (position == imgsRes.length - 1) {
                    isJump = true;
                } else {
                    isJump = false;
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });

        setAdPic(pics);
    }

    @Override
    protected void initInject() {
        setContentView(R.layout.activity_splash_ad);
        ButterKnife.bind(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (myCountDownTimer != null) {
            myCountDownTimer.cancel();
        }

    }

    private void initUser() {
        UserManager.init(this);
        int version = DeviceHelper.getInstance(this).getAppVersion();
        int temp = SharedPreferencesUtil.getSharedPreferenceInstance(this).getInt("versionTemp", 0);
        if (version > temp) {
            if (UserManager.isLoginS()) {
                UserManager.getInstance().setUser(this, null);
                UserManager.getInstance().delUserCache(this);
            }
            SharedPreferencesUtil.setParams(this, "versionTemp", version);
        }
    }

    boolean hasExit = false;

    private void toMain() {
        if (hasExit) {
            return;
        }
        myCountDownTimer = null;
        Intent intent = new Intent(this, MainActivity.class);
        startActivity(intent);
        hasExit = true;
        finish();

    }


    /**
     * 设置轮播图片
     *
     * @param woAdavertising
     */
    private void setAdPic(List<Integer> woAdavertising) {
        if (woAdavertising != null) {
            try {
                setBannerPic(woAdavertising);

            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }

    private synchronized void startCuntDown(int pos, int length) {

        if (cuntDownRunable != null) {
            handler.removeCallbacks(cuntDownRunable);
        }
        if (!isFirstStart) {
            cuntDownRunable = new CuntDownTask(pos, length);
        }

        handler.post(cuntDownRunable);
    }

    private synchronized void onCountDownFinish(int currentPos) {
        if (hasCallFinish) {
            return;
        }
        toMain();
        finish();
        hasCallFinish = true;

    }


    //设置轮播资源
    private void setBannerPic(final List<Integer> wad) {


        if (wad != null && wad.size() > 0) {
            splash_images.setPages(new CBViewHolderCreator() {
                @Override
                public Object createHolder() {
                    return new AdInfoHolder();
                }
            }, wad)
                    .setPageIndicatorAlign(ConvenientBanner.PageIndicatorAlign.ALIGN_PARENT_RIGHT);
//设置点击事件
            splash_images.setOnItemClickListener(new OnItemClickListener() {
                @Override
                public void onItemClick(int position) {
                    if (isJump && isFirstStart) {
                        SharedPreferencesUtil.setParam(SplashAdActivity.this, START_KEY, false);
                        toMain();
                    }
                }
            });
            splash_images.hideBottom(true);

//设置自动跳转时间
            adCount = wad.size();
            startCuntDown(adCount, time);
            if (!splash_images.isTurning() && !isFirstStart) {
                splash_images.startTurning(time * 1000);
            }
        }


    }

    @Event(value = {R.id.splash_skip})
    private void onClick(View view) {
        if (myCountDownTimer != null) {
            myCountDownTimer.cancel();
        }
        onCountDownFinish(0);
    }

    private class CuntDownTask implements Runnable {
        private int adPos;
        private int showTime;
        private int count;

        public CuntDownTask(int showTime) {
            this.showTime = showTime;
        }

        public CuntDownTask(int adPos, int showTime) {
            Log.e("CuntDownTask", "adPos:" + adPos + " showTime:" + showTime);
            this.adPos = adPos;
            this.showTime = showTime;
            count = showTime;
        }

        public void setCountDownInfo(int adPos, int showTime) {
            this.adPos = adPos;
            this.showTime = showTime;
            count = showTime;
        }

        @Override
        public void run() {
            time_tv.setText(count + "");
            count--;
            if (count > 0) {
                handler.postDelayed(this, 1000);
            } else {
                adPos--;
                if (adPos <= 0) {
                    onCountDownFinish(adPos);
                } else {
                    count = showTime;
                    handler.postDelayed(this, 1000);
                }

            }

        }
    }

    /**
     * 设置倒计时
     */
    class MyCountDownTimer extends CountDownTimer {


        public MyCountDownTimer(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            int time = (int) millisUntilFinished / 1000;
            time_tv.setText(time + "");
            JLog.e("-----time--" + time);
        }

        @Override
        public void onFinish() {
            time_tv.setText(0 + "");
           /* toMain();
            finish();*/

        }
    }


    @Override
    protected void onDestroy() {
        if (splash_images != null && splash_images.isTurning()) {
            splash_images.stopTurning();
        }
        if (cuntDownRunable != null) {
            handler.removeCallbacks(cuntDownRunable);
            cuntDownRunable = null;
        }
        super.onDestroy();
    }

    public class AdList {
        private int resId;

        public int getResId() {
            return resId;
        }

        public void setResId(int resId) {
            this.resId = resId;
        }
    }
}
